import { Ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

import useRequest from "./useRequest";

type TUseDeleteOptions = {
  title?: string;
  content?: string;

  refresh?: () => void;
};

export default function useDelete(
  url: string | Ref<string>,
  {
    title = "删除提示",
    content = "确定执行删除操作吗？",

    refresh,
  }: TUseDeleteOptions = {}
) {
  const { isFetching, lastParams, run, onFetchResponse, onFetchError } =
    useRequest(url, {
      immediate: false,
    });

  const del = async (params: any) => {
    if (isFetching.value) {
      ElMessage.info("上一个任务尚未结束");
      return;
    }

    await ElMessageBox.confirm(content, title, {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    run(params);
  };

  onFetchResponse(() => {
    ElMessage.success("删除成功！");
    refresh?.();
  });

  onFetchError(() => {
    ElMessage.error("删除失败！");
  });

  return {
    del,
    onFetchResponse,
    delParams: lastParams,
    isFetching,
  };
}
